/**
 * 14/02/2014
 * 
 * StockDAO
 */
package org.cuatrovientos.erp.dao;

import java.util.List;

import org.cuatrovientos.erp.model.Stock;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

/**
 * Implementation of StockDAO
 * @author Inaki Torres
 */
public class StockDAO implements StockDAOInterface {

	@Autowired
	private SessionFactory sessionFactory;


	/**
	 * Constructor
	 */
	public StockDAO () {

	}

	/**
	 * returns Hibernate session
	 * @return
	 */
	private Session getSession () {
		return sessionFactory.getCurrentSession();
	}

	/* (non-Javadoc)
	 * @see org.cuatrovientos.erp.dao.StockDAOInterface#selectById(int)
	 */
	@Transactional(readOnly = true)
	public Stock selectById(int id) {
		Stock shipment = (Stock) getSession().get(Stock.class, id);
		return shipment;
	}

	/* (non-Javadoc)
	 * @see org.cuatrovientos.erp.dao.StockDAOInterface#selectAll()
	 */
	@Transactional(readOnly = true)
	public List<Stock> selectAll() {
		List<Stock> stock = getSession().createQuery("from Stock").list();
		return stock;
	}

	/* (non-Javadoc)
	 * @see org.cuatrovientos.erp.dao.StockDAOInterface#selectAllCount()
	 */
	@Transactional(readOnly = true)
	public int selectAllCount() {
		List<Stock> stock = getSession().createQuery("from Stock").list();
		return stock.size();
	}

	/* (non-Javadoc)
	 * @see org.cuatrovientos.erp.dao.StockDAOInterface#insert(org.cuatrovientos.erp.model.Stock)
	 */
	@Transactional
	public void insert(Stock stock) {
		Integer id = (Integer) getSession().save(stock);
		stock.setId(id);           
	}

	/* (non-Javadoc)
	 * @see org.cuatrovientos.erp.dao.StockDAOInterface#update(org.cuatrovientos.erp.model.Stock)
	 */
	@Transactional
	public void update(Stock stock) {
		getSession().merge(stock);
	}

	/* (non-Javadoc)
	 * @see org.cuatrovientos.erp.dao.StockDAOInterface#delete(org.cuatrovientos.erp.model.Stock)
	 */
	@Transactional
	public void delete(Stock stock) {
		getSession().delete(stock);
	}

	/* (non-Javadoc)
	 * @see org.cuatrovientos.erp.dao.StockDAOInterface#saveOrUpdate(org.cuatrovientos.erp.model.Stock)
	 */
	@Transactional
	public void saveOrUpdate(Stock stock) {
		getSession().saveOrUpdate(stock);
	}

	/* (non-Javadoc)
	 * @see org.cuatrovientos.erp.dao.StockDAOInterface#deleteById(int)
	 */
	@Transactional
	public void deleteById(int id) {
		Stock stock = (Stock) getSession().load(Stock.class,id);
		getSession().delete(stock);
	}

	/* (non-Javadoc)
	 * @see org.cuatrovientos.erp.dao.StockDAOInterface#search(java.lang.String)
	 */
	@Transactional(readOnly = true)
	public List<Stock> search(String name) {
		Query query = 
				getSession().
				createQuery("from Stock s where s.name like :name");
		
		query.setParameter("name", "%" + name + "%");

		List<Stock> stock = query.list();

		return stock;
	}

}
